package com.tdrc.common.core.shiro;

import com.alibaba.druid.util.StringUtils;
import com.tdrc.common.beans.Audience;
import com.tdrc.common.beans.ResultCode;
import com.tdrc.common.beans.User;
import com.tdrc.common.service.UserService;
import com.tdrc.common.util.HttpServletResponseUtil;
import com.tdrc.common.util.JsonResult;
import com.tdrc.common.util.JwtTokenUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


/**
 * @author dpf
 * @version 1.0
 * @date 2020-5-22 15:21
 * @instruction ...
 */
public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private Audience audience;
    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        System.out.println("————身份认证方法————");
        String token = (String) authenticationToken.getCredentials();
        // 验证token的有效性，如果无效会抛出异常
            JwtTokenUtil.parseJWT(token,audience.getBase64Secret());
            if(JwtTokenUtil.isExpiration(token,audience.getBase64Secret())){
                throw new AuthenticationException("token过期");
            }
        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("########################权限认证############################");
        String userId = JwtTokenUtil.getUserId(principals.toString(), audience.getBase64Secret());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
         info.addStringPermission("/user/list");
        return info;
    }

}
